using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;

public class NetPackage
{
    private static int[] pkgPoolSizes = {1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15, 1<<16};
    private static Dictionary<short, Queue<NetPackage>> pkgPools = new Dictionary<short, Queue<NetPackage>>();
    private short key;
    public byte[] data { get; private set; }
    public int size { get; private set; }

    public NetPackage(short key)
    {
        this.key = key;
        data = new byte[pkgPoolSizes[key]];
    }

    private static short GetPkgPoolKey(int size)
    {
        for (short index=0; index<pkgPoolSizes.Length; index++)
        {
            if (pkgPoolSizes[index] >= size)
            {
                return index;
            }
        }
        return -1;
    }

    public void FillBytes(byte[] bytes)
    {
        var len = bytes.Length;
        Array.Copy(bytes, 0, data, size, len);
        size += len;
    }

    public static NetPackage Create(byte[] buffer)
    {
        NetPackage netPackage = null; 
        var key = GetPkgPoolKey(buffer.Length);
        netPackage = pkgPools.TryGetValue(key, out var netPackages) && netPackages.Count > 0 ? netPackages.Dequeue() : new NetPackage(key);
        netPackage?.FillBytes(buffer);
        return netPackage;
    }

    public void Release()
    {
        Clear();
        if (!pkgPools.TryGetValue(key, out var netPackages))
        {
            netPackages = new Queue<NetPackage>();
            pkgPools.Add(key, netPackages);
        }
        netPackages.Enqueue(this);
    }

    public void Clear()
    {
        size = 0;
        Array.Clear(data, 0, data.Length);
    }
}
